package com.ccl.iot.device;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;

import com.ccl.iot.privates.BitmapBuilder;

public class SwitchControler extends DeviceControler{
	/*
	 * 	Static functions
	 */
	public static boolean RegisterControlerType(){
		RegisterControlerType(BatchIntentionDevice.class);
		return RegisterControlerType(SwitchControler.class);
	}
	
	/*
	 * 	Non-static functions
	 */
	private IOTSwitch iDevice;
		
	public SwitchControler(IOTSwitch aDevice) {
		super(aDevice);
		
		iDevice = aDevice;
	}
	
	@Override
	protected boolean onTouchDown(float aX, float aY){
		onBitmapChange();
		
		return true;
	}
	
	@Override
	protected boolean onTouchMove(float aX, float aY){
		return true;
	}
	
	@Override
	protected boolean onTouchUp(float aX, float aY){
		if (iDevice != null){
			iDevice.turn(iDevice.isOn() == false);
		}
		
		onBitmapChange();
		
		return true;
	}
	
	protected boolean onTouchCancel(float aX, float aY){
		onBitmapChange();
		
		return true;
	}
	
	@Override
	public Bitmap getBitmap(int aWidth, int aHeight){
		if (aWidth > 0 && aHeight > 0 && iDevice != null){
			Bitmap tBackground = Bitmap.createBitmap(aWidth, aHeight, Config.RGB_565);
			Canvas tCanvas = new Canvas(tBackground);
			Bitmap tBitmap = null;
			Rect tPadding = super.getPadding();
			int tWidth = Math.abs(aWidth - tPadding.left - tPadding.right);
			int tHeight = Math.abs(aHeight - tPadding.top - tPadding.bottom);
			
			if (iDevice.getImageCount() == 0){
				tCanvas.drawColor(super.getBackColor());
				tBitmap = SwitchIconProvider.Build(iDevice, DeviceIconProvider.KICON_STYLE_DEFAULT, tWidth, tHeight, super.getBackColor(), isTouchDown());
			}else{
				tBitmap = BitmapBuilder.GetBitmap(iDevice.getImage(), tWidth, tHeight, true);
				tCanvas.drawColor(SwitchIconProvider.GetHighLigthColor(iDevice, isTouchDown()));
			}
			
			if (tBitmap != null){
				tCanvas.drawBitmap(tBitmap, tPadding.top, tPadding.bottom, new Paint());
//				tBitmap.recycle();
			}
			
			tCanvas.save();
			tCanvas.restore();
			
			return tBackground;
		}
		
		return null;
	}
}
